<script setup lang="ts">
import { ref, onMounted } from "vue";
import { debounce } from "lodash-es";
import VueSimpleVerify from "@/components/SimpleVerify/index.vue";
import { useRouter, useRoute } from "vue-router";
import { useUserStore } from "@/stores/modules/user";
import { ElNotification } from "element-plus";
import { User, Lock } from "@element-plus/icons-vue";
import { useAppStore } from "@/stores/app";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const appStore = useAppStore();

// 设置 CSS 变量
// const root = document.documentElement;
// root.style.setProperty('--text-color-primary', '#fff');

const loginForm = ref({
  username: "admin",
  password: "123456",
  captcha: "1234",
  rememberMe: false,
});

const loginRules = ref({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

const loading = ref(false);
const loginFormRef = ref();

const verifyRef = ref(null);
const verifyState = ref(false);
const verifyError = ref(false);

onMounted(() => {
  appStore.setLoading(true);
});
const handleSuccess = () => {
  console.log("success");
  verifyError.value = false;
  verifyState.value = true;
};
const handleReset = () => {
  console.log("reset");
  onReset();
};
const onReset = () => {
  if (verifyRef.value) {
    setTimeout(() => {
      (verifyRef.value as any)?.reset();
    }, 750);
  }
};
// 提交，添加防抖
const onSubmit = debounce(async () => {
  console.log("submit");
  loginFormRef.value?.validate(async (valid: boolean) => {
    console.log(valid);
    if (valid) {
      if (!verifyState.value) {
        verifyError.value = true;
        ElNotification({
          title: "Error",
          message: "请请完成验证",
          type: "error",
        });
        return true;
      }
      // 检测通过
      handleLogin();
    } else {
      ElNotification({
        title: "Error",
        message: "请输入用户名/密码",
        type: "error",
      });
    }
  });
}, 500);

const handleLogin = async () => {
  console.log("登录中...");
  loading.value = true;
  try {    
    console.log("登录参数", loginForm.value);
    const res = await userStore.login({ type: "password", ...loginForm.value });
    console.log("success", res);
    if (res) {
      ElNotification({
        title: "Success",
        message: "登录成功",
        type: "success",
      });
      appStore.setLoading(true);
      const redirect = route.query.redirect || "/";
      console.log("redirect", redirect);
      router.push(redirect as string);
    } else {
      ElNotification({
        title: "Error",
        message: "用户名或密码错误",
        type: "error",
      });
      onReset(); // 重置验证状态
    }
  } catch (error: any) {
    console.log(error);
    loading.value = false;
    onReset(); // 重置验证状态
  } finally {
    loading.value = false;
  }
};
</script>
<template>
  <div class="auth-box">
    <div class="p-t"></div>
    <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="auth-form">
      <div class="title">
        <h3 class="">管理系统</h3>
      </div>
      <el-form-item prop="username" class="pb-1.5">
        <el-input
          v-model="loginForm.username"
          placeholder="用户名"
          size="large"
          :prefix-icon="User"
        />
      </el-form-item>

      <el-form-item prop="password" class="pb-1.5">
        <el-input
          v-model="loginForm.password"
          type="password"
          placeholder="密码"
          size="large"
          :prefix-icon="Lock"
          show-password
          @keyup.enter="handleLogin"
        />
      </el-form-item>
      <el-form-item class="pb-1.5">
        <VueSimpleVerify
          ref="verifyRef"
          borderColor="#00000073"
          bgColor="#00000013"
          @success="handleSuccess"
          @reset="handleReset"
        ></VueSimpleVerify>
        <div class="el-form-item__error" v-if="!verifyState && verifyError">
          请完成验证
        </div>
      </el-form-item>
      <el-form-item>
        <div class="flex justify-between items-center w-full">
          <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
          <el-link type="primary" class="text-blue" href="/forget">忘记密码?</el-link>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button
          :loading="loading"
          type="primary"
          class="submit-btn mx-auto"
          @click="onSubmit"
        >
          {{ loading ? "登录中..." : "登录" }}
        </el-button>
      </el-form-item>
    </el-form>
    <div class="flex justify-center items-center px-10 opacity-70">
      <span class="line w-1/3"></span>
      <span class="flex-1 text-center text-white text-sm">其他登录方式</span>
      <span class="line w-1/3"></span>
    </div>
    <div class="flex justify-center items-center py-2.5">
      <el-tooltip class="box-item" effect="dark" content="微信登录" placement="top">
        <div
          class="hover:bg-gray-300/30 rounded-xl transition flex ml-3.5 cursor-pointer"
          style="height: 32px; width: 32px"
        >
          <span class="i-codicon-refresh text-4.5 text-icon m-auto text-white"></span>
        </div>
      </el-tooltip>
      <el-tooltip class="box-item" effect="dark" content="QQ登录" placement="top">
        <div
          class="hover:bg-gray-300/30 rounded-xl transition flex ml-3.5 cursor-pointer"
          style="height: 32px; width: 32px"
        >
          <span class="i-codicon-refresh text-4.5 text-icon m-auto text-white"></span>
        </div>
      </el-tooltip>
      <el-tooltip class="box-item" effect="dark" content="Github登录" placement="top">
        <div
          class="hover:bg-gray-300/30 rounded-xl transition flex ml-3.5 cursor-pointer"
          style="height: 32px; width: 32px"
        >
          <span class="i-codicon-refresh text-4.5 text-icon m-auto text-white"></span>
        </div>
      </el-tooltip>
      <el-tooltip class="box-item" effect="dark" content="Google登录" placement="top">
        <div
          class="hover:bg-gray-300/30 rounded-xl transition flex ml-3.5 cursor-pointer"
          style="height: 32px; width: 32px"
        >
          <span class="i-codicon-refresh text-4.5 text-icon m-auto text-white"></span>
        </div>
      </el-tooltip>
    </div>
    <div class="flex justify-center">
      <span class="text-sm pr-1.5 text-white">还没有账号? </span>
      <router-link to="/register" class="text-blue text-sm">注册</router-link>
    </div>
    <div class="h-15"></div>
    <div class="p-b"></div>
  </div>
</template>

<style lang="scss" scoped>
@use '@/styles/layout/auth.scss';
:root {
  --text-color-primary: #fff !important;
}
.text-white {
  color: #fff !important;
}
.text-blue {
  color: #409eff !important;
}
:deep(.el-popper) {
  color: #fff !important;
}
</style>
